#include "SSD1306Wire.h"    //0.96寸用这个

#include <ArduinoJson.h>
#include <Arduino.h>
#include <Ticker.h>
#include <sstream>
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <ESP8266WiFiMulti.h>
#include <WiFiClientSecure.h>

#include <ESPAsyncTCP.h>
#include <string.h>
#include <ESPAsyncWebServer.h>
#include "FS.h"
#include <LittleFS.h>
#include <TimeLib.h>
#include <Wire.h>  // Only needed for Arduino 1.6.5 and earlier
#include "SSD1306Wire.h" // legacy include: `#include "SSD1306.h"`
#include "OLEDDisplayUi.h"
#include "font_cn.h"
#include "Constas.h"

#define DEMO_DURATION 3000

WiFiClient wifiClient;
SSD1306Wire display(0x3c, SDA, SCL);
OLEDDisplayUi ui ( &display );

// AP Server 配置
char* AP_SSID = "guiyn-mark1";
IPAddress AP_LOCAL_IP(192, 168, 10, 1); //手动设置的开启的网络的ip地址
IPAddress AP_GATEWAY(192, 168, 10, 1); //手动设置的网关IP地址
IPAddress AP_SUBNET(255, 255, 255, 0); //手动设置的子网掩码

//WIFI STA clien 配置
String WIFI_STA_SID_VAL;
String WIFI_STA_SID_PASS_VAL;
String WIFI_STA_SID_KEY = "WIFI_STA_SID";
String WIFI_STA_SID_PASS_KEY = "WIFI_STA_SID_PASS";


// html 页面文件名
String SETTING_FILE_NAME = "/wifi_setting.html"; //设置文件文件名称
String CONF_WIFI_FILE_NAME = "/wifi_conf.json";

String SETTING_PAGE;  // 设置文件文件内容
String WIFI_SCAN_JSON;

// WIFI状态
String WIFI_STATUS_STR;

// AP按钮按下次数
unsigned int AP_BUTTON_ONCLICK_NUM = 0;
// AP 服务空闲时间
unsigned int AP_IDLE_NUM = 0;
unsigned long STA_CONNECTION_TIME = 0;
//控制标识
boolean START_AP_CTRL = false;
boolean START_WIFI_STA_CTRL = false;





String WDAY_NAMES[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};  //星期
String MONTH_NAMES[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};  //月份

long update_time = 0;

AsyncWebServer server(80);
Ticker ticker;
void my_init() {
  Serial.begin(115200); // 打开串口
  delay(1000);
  Serial.println(">>>>>闹钟系统启动");
  //引脚设置
  //Serial.println(">>>>>引脚设置开始");
  //按钮
  pinMode(D6, INPUT);
  //灯
  pinMode(D7, OUTPUT);
  digitalWrite(D7, HIGH);
  //  Serial.println(">>>>>>按钮 D6 指示灯 D2 设置完成");
  if (SPIFFS.begin()) {
    showFSInfo();
  }
  else
  {
    Serial.println("ERROR :: SPIFFS 文件系统获取失败");
    return;
  }

  Serial.println("SDA >>>> " + String( SDA));
  Serial.println("SCL >>>> " + String( SCL));


  // 读取 wifi sta配置
  if (loadWifiStaJsonConf()) {
    Serial.println(">>>>获取以配置WIFI信息成功");
    START_WIFI_STA_CTRL = true;
    wifiBegin(WIFI_STA_SID_VAL, WIFI_STA_SID_PASS_VAL);
    // wifi 已经链接
    if (WiFi.status() == WL_CONNECTED )
    {
      // 获取一次HTTPS 数据内容
      getWatherNow();
      getTimeNow();
      getLife();
      getDAily();
    }
    else
    {
      // 开启你配置网络
      servletSet() ;
      server.begin();
      // wifi 链接失败启动AP 模式
      startWiFiAp();
    }
  }
  else
  {
    // 开启你配置网络
    servletSet() ;
    server.begin();
    // 加载html 页面文件
    startWiFiAp();
  }
  // 启动一个按钮监控ticker
  ticker.attach_ms(100, apButtonClick);
}

//启动wifi ap 模式并亮灯
void startWiFiAp()
{
  display.clear();
  display.setFont(ArialMT_Plain_24);
  display.setTextAlignment(TEXT_ALIGN_CENTER);
  display.drawString(64, 0, "Setting...");
  display.setFont(ArialMT_Plain_16);
  display.setTextAlignment(TEXT_ALIGN_RIGHT);
  display.drawString(128, 26, String( AP_SSID));
  display.setTextAlignment(TEXT_ALIGN_RIGHT);
  display.drawString(128, 44, String( "192.168.10.1" ));
  display.display();
  SETTING_PAGE = loadFile(SETTING_FILE_NAME);
  Serial.println(">>>>>加载配置WIFI页面完成");
  startApServer(AP_SSID, AP_LOCAL_IP, AP_GATEWAY, AP_SUBNET);
}



//按钮监控事件 弱长按 触发翻页动作
void apButtonClick()
{
  if (digitalRead(D6) == 1)
  {
    AP_BUTTON_ONCLICK_NUM++;
    if (AP_BUTTON_ONCLICK_NUM == 2)
    {

      Serial.println("click ap button ....  ");
      AP_BUTTON_ONCLICK_NUM = 0;
      ui.nextFrame();
    }
  }

}

double _y = 0;
// 界面顺序
FrameCallback frames[] = {drawWatherTime,  watherToday, lifeinfo, watherTomorrowAndAfterTomorrow, bigClock};
int frameCount = 5;

void clockOverlay(OLEDDisplay *display, OLEDDisplayUiState* state) {

}
OverlayCallback overlays[] = { clockOverlay };
int overlaysCount = 1;

void setup() {

  ui.setTargetFPS(60);
  ui.setActiveSymbol(activeSymbol);
  ui.setInactiveSymbol(inactiveSymbol);
  ui.setIndicatorPosition(TOP);
  ui.setIndicatorDirection(LEFT_RIGHT);
  //ANIMATION_inactiveSymbol
  ui.setActiveSymbol(animation_inactive_symbol);
  ui.setFrameAnimation(SLIDE_LEFT);
  ui.setFrames(frames, frameCount);
  ui.setOverlays(overlays, overlaysCount);
  ui.disableAutoTransition();
  ui.init();
  display.init();
  display.flipScreenVertically();
  welcome();
  display.display();
  my_init();

}

long interval = 600000;
unsigned long previousMillis = 0;
unsigned long previousMillis2 = 0;
void loop() {

  ui.update();

  unsigned long currentMillis = millis();
  if (currentMillis - previousMillis >= interval)
  {

    previousMillis = currentMillis;
    wifiScan();
    getTimeNow();
    getWatherNow();
    getLife();
    getDAily();
  }



  if (currentMillis - previousMillis2 >= interval * 36)
  {
    previousMillis2 = currentMillis;
    getLife();
    getDAily();
  }

}
